<template>
  <div class="base-container" id="main">
    <div style="display: flex;font-weight: bold;color: #000000;justify-content: center;font-size: 29px;padding: 20px">
      江 西 省 地 方 标 准 报 批 表
    </div>
    <div
      style="display: flex;font-weight: bold;color: #000000;justify-content: center;font-size: 21px;margin-bottom: 10px;">
      （试行）
    </div>
    <t-form labelAlign="top" ref="form" :data="formData" :rules="rules" class="step-form table-form"
            labelWidth="140px">
      <t-row>
        <t-col :span="2" class="title">标准名称</t-col>
        <t-col :span="4">
          <t-form-item name="projectName">
            {{ formData.projectName }}
          </t-form-item>
        </t-col>
        <t-col :span="2" class="title"><span class="require">*</span>标准号</t-col>
        <t-col :span="4">
          <t-form-item name="standardNum">
            <t-input clearable v-model="formData.standardNum"></t-input>
          </t-form-item>
        </t-col>
      </t-row>
      <t-row>
        <t-col :span="2" class="title"><span class="require">*</span>报批日期</t-col>
        <t-col :span="10">
          <t-form-item name="submitDate">
            <t-date-picker style="width: 390px" clearable v-model="formData.submitDate"></t-date-picker>
          </t-form-item>
        </t-col>
      </t-row>
      <t-row>
        <t-col :span="2" class="title"><span class="require">*</span>任务来源<br/>计划项目编号</t-col>
        <t-col :span="10">
          <t-form-item name="projectNum">
            <t-input clearable v-model="formData.projectNum"></t-input>
          </t-form-item>
        </t-col>
      </t-row>
      <t-row>
        <t-col :span="2" class="title"><span class="require">*</span>主要起草单位</t-col>
        <t-col :span="10">
          <standard-company ref="standard-company" tableSize="small" v-model="formData.draftUnits" :editOpen="true"></standard-company>
          <!-- <t-tree-select clearable @change="(val,content)=>{formData.unitName=content.node.data.unitName}" filterable :treeProps="{ keys: { value: 'unitId', label: 'unitName' } }"
                         v-model="formData.unitId" :data="deptMenuOptions" placeholder="选择主要起草单位"></t-tree-select> -->
        </t-col>
      </t-row>
      <t-row>
        <t-col :span="2" class="title"><span class="require">*</span>项目负责人</t-col>
        <t-col :span="4">
          <t-form-item name="projectLeader">
            <t-input clearable v-model="formData.projectLeader"></t-input>
          </t-form-item>
        </t-col>
        <t-col :span="2" class="title"><span class="require">*</span>联系电话</t-col>
        <t-col :span="4">
          <t-form-item name="phone">
            <t-input clearable v-model="formData.phone"></t-input>
          </t-form-item>
        </t-col>
      </t-row>
      <t-row>
        <t-col :span="2" class="title"><span class="require">*</span>相关附件</t-col>
        <t-col :span="10">
          <t-table size="small" row-key="id" :columns="projectFileColumns" :data="projectFileData">
            <template #id="{row, rowIndex}">
              {{ rowIndex + 1 }}
            </template>
            <template #op="{row}">
              <file-upload v-model="row.fileIds" :moduleKey="row.moduleKey"
                           :fileList="row.fileLists"
                           :multiple="true">
                <t-button variant="outline">
                  <t-icon name="cloud-upload" slot="icon"/>
                  点击上传
                </t-button>
              </file-upload>
            </template>
            <template #c1="{row}">
              <a v-if="row.c3" class="t-button-link" :href="`${file_domain}/${row.c3}`" target="_blank">{{ row.c1 }}</a>
              <div v-else>{{ row.c1 }}</div>
            </template>
          </t-table>
        </t-col>
      </t-row>
    </t-form>
    <t-row style="margin-top: 20px;text-align: center">
      <t-col :span="12">
        <t-space :size="10">
          <t-button theme="primary" :loading="applyLoading" @click="onSubmit(1)">{{
              applyLoading ? '提交中...' : '暂存'
            }}
          </t-button>
          <t-button theme="primary" :loading="applyLoading" @click="onSubmit(2)">{{
              applyLoading ? '提交中...' : '提交'
            }}
          </t-button>
        </t-space>
      </t-col>
    </t-row>
  </div>
</template>

<script>
import { VITE_FILE_DOMAIN } from '@/api/upload'
import standardCompany from "@/pages/bzh/standard/components/standard-company.vue";
import memberList from "../../components/member-list.vue";
import {getFiles} from "@/api/common";
import FileUpload from "@/components/FileUpload/index.vue"

export default {
  name: "submit-apply",
  components:{
    standardCompany,
    memberList,
    FileUpload
  },
  data() {
    return {
      file_domain: VITE_FILE_DOMAIN,
      projectFileData: [
        {
          id: 1,
          c1: "报批表",
          c2: "是",
          fileIds: [],
          fileLists: [],
          moduleKey: "projectBPB",
          require: true,
        },
        {
          id: 2,
          c1: "报批稿",
          c2: "是",
          fileIds: [],
          fileLists: [],
          moduleKey: "projectBPG",
          require: true,
        },
        {
          id: 3,
          c1: "编制说明",
          c2: "是",
          fileIds: [],
          fileLists: [],
          moduleKey: "projectBZSM",
          require: true,
        },
        {
          id: 4,
          c1: "其他",
          c2: "否",
          fileIds: [],
          fileLists: [],
          moduleKey: "projectOther",
          require: false,
        },
      ],
      projectFileColumns: [
        {
          colKey: "id",
          title: "序号",
          align: "center",
          width: 64
        },
        {
          colKey: "c1",
          title: "附件名称",
          align: "center",
        },

        {
          colKey: "c2",
          title: "是否必需",
          align: "center",
        },
        {
          colKey: "op",
          title: "操作",
          align: "left",
        },
      ],
      applyLoading: false,
      formData: {
        localId: null,
        taskSource: '',
        projectNum: '',
        projectLeader: '',
        phone: '',
        unitId: null,
        draftUnits: [],
        technologyIndex: '',
        expectedGoal: '',
        suggestion: '',
        submitDate: '',
        standardNum: '',
      },
      rules: {
        submitDate: [
          {
            required: true,
            message: "报批日期不能为空",
          },
        ],
        standardNum: [
          { required: true, message: "标准号不能为空" }
        ],
        projectNum: [
          { required: true, message: "任务来源/计划项目编号不能为空" }
        ],
        projectLeader: [
          { required: true, message: "项目负责人不能为空"}
        ],
        phone: [
          {
            required: true,
            message: "联系电话不能为空",
          },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "联系电话请输入正确的手机号码",
          },
        ],
      },
      draftUnitId: null,
    }
  },
  created() {
    const taskId = this.$route.params && this.$route.params.taskId;
    if (!taskId) {
      this.$message.error("缺少id");
      this.close();
      return false;
    }
    this.formData.localId = taskId;
    this.$api.bzh.submit.getBySuggestId(taskId).then(response => {
      if (!response.data) {
        // 获取报审信息
        this.$api.bzh.report.getBySuggestId(taskId).then(res => {
          if (!res.data) {
            return false;
          }
          this.formData.taskSource = res.data.taskSource;
          this.formData.projectNum = res.data.projectNum;
          this.formData.projectLeader = res.data.projectLeader;
          this.formData.phone = res.data.phone;
          this.formData.unitId = res.data.unitId;
          this.formData.unitName = res.data.unitName;
        }).catch(e => {
          this.$message.error(e.toString())
        })
        return false;
      }
      this.formData = Object.assign({}, this.formData, response.data)


      getFiles(response.data.id).then((res) => {
        const files = {}
        res.data.forEach((item) => {
          if (!files[item.moduleKey]) {
            files[item.moduleKey] = []
          }
          files[item.moduleKey].push({
            name: item.fileName,
            url: item.fullFilePath,
            id: item.id,
            filePath: item.filePath
          })
        })
        this.projectFileData.forEach((val, index) => {
          this.projectFileData[index].fileLists = files[val.moduleKey] || [];
          this.projectFileData[index].fileIds = files[val.moduleKey]?.map(val => val.id) || [];
        })
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    }).catch(e => {
      this.$message.error(e.toString())
    })

    this.$api.bzh.standard.getApplyBySuggestId(taskId).then(res => {
      if (!res.data) {
        return false;
      }
      this.formData.projectName = res.data.projectName;
      this.formData.draftUnits = res.data.draftUnits;
    }).catch(e => {
      this.$message.error(e.toString())
    })
  },
  methods:{
    onSubmit(type) {
      const sysAttMainIds = []
      this.projectFileData.forEach(val=>{
        sysAttMainIds.push(...val.fileIds)
      })
      if (type === 1) {
        this.applyLoading = true;
        if (!this.formData.id) {
          this.$api.bzh.submit.add({
            ...this.formData,
            sysAttMainVo: {
              sysAttMainIds
            }
          }).then(response => {
            this.formData.id = response.data.id;
            this.applyLoading = false;
            this.$message.success('暂存成功');
          }).catch((e) => {
            this.applyLoading = false;
            this.$message.error(e.toString());
          });
        } else {
          this.$api.bzh.submit.update({
            ...this.formData,
            sysAttMainVo: {
              sysAttMainIds
            }
          }).then(response => {
            this.applyLoading = false;
            this.$message.success('暂存成功');
          }).catch((e) => {
            this.applyLoading = false;
            this.$message.error(e.toString());
          });
        }
      } else {
        this.$refs.form.validate().then((validateResult) => {
          if (validateResult === true) {
            const isValidate2 = this.projectFileData.every(val => {
              if (val.require && val.fileIds.length <= 0) {
                this.$message.error(`需要上传${val.c1}`);
                return false;
              }
              return true
            })
            if (!isValidate2) {
              return false
            }
            const confirmDia = this.$dialog.confirm({
              header: "提交后不可再编辑，会自动进入到下一阶段",
              body: `是否确认提交？`,
              theme: "warning",
              onConfirm: ({e}) => {
                confirmDia.update({
                  confirmBtn: {
                    loading: true,
                  },
                })
                this.applyLoading = true;
                this.$api.bzh.submit.submit({
                  ...this.formData,
                  sysAttMainVo: {
                    sysAttMainIds
                  }
                }).then(response => {
                  this.applyLoading = false;
                  confirmDia.destroy();
                  this.$message.success('提交成功');
                  this.close();
                }).catch((e) => {
                  this.applyLoading = false;
                  confirmDia.update({
                    confirmBtn: {
                      loading: false,
                    },
                  })
                  this.$message.error(e.toString());
                });
              },
            })


          } else {
            const firstError = Object.values(validateResult)[0]?.[0]?.message;
            this.$message.error(firstError);
          }
        });
      }
    },
    close() {
      this.$tab.closeOpenPage({path: "/bzh/submit/submit-my"});
    }
  }
}
</script>

<style scoped>

</style>
